<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <p align="center">
        省:<select id="sel1">
            <option value="">请选择</option>
        </select> 市:
        <select id="sel2"></select> 区:
        <select id="sel3"></select>
    </p>
    您选择的地址是：
    <h1 id="address"></h1>
</body>
<script src="js/city.js"></script>
<script>
    var sel1 = document.getElementById('sel1');
    var sel2 = document.getElementById('sel2');
    var sel3 = document.getElementById('sel3');
    var h1 = document.getElementById('address');
    var cityArr = [];
    var areaArr = [];

    citys.forEach(v => {
        var option = new Option(v.name);
        sel1.options.add(option); //显示的省
    })
    var sel1Index = 0;
    //省改变的时候
    sel1.onchange = function() {
            sel1Index = this.selectedIndex - 1;
            sel2.options.length = 0;
            sel3.options.length = 0;
            if (sel1Index != -1) {
                cityArr = citys[sel1Index].city;
                cityArr.forEach(v => {
                    var option = new Option(v.name);
                    sel2.options.add(option); //显示的市
                })

                areaArr = cityArr[0].districtAndCounty;
                areaArr.forEach(v => {
                    var option = new Option(v);
                    sel3.options.add(option); //显示的区
                })
                h1.innerHTML = citys[sel1Index].name + cityArr[0].name + areaArr[0];
            } else {
                h1.innerHTML = "";
            }
        }
        // 市改变的时候
    var sel2Index = 0;
    sel2.onchange = function() {
            sel2Index = this.selectedIndex;
            areaArr = cityArr[sel2Index].districtAndCounty;
            sel3.options.length = 0;
            areaArr.forEach(v => {
                var option = new Option(v);
                sel3.options.add(option); //显示的区
            })
            h1.innerHTML = citys[sel1Index].name + cityArr[sel2Index].name + areaArr[0];
        }
        //区改变的时候
    var sel3Index = 0;
    sel3.onchange = function() {
        sel3Index = this.selectedIndex;
        h1.innerHTML = citys[sel1Index].name + cityArr[sel2Index].name + areaArr[sel3Index];
    }
</script>

</html>